package com.esaheki.flashcards.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.esaheki.flashcards.classes.*;
import com.esaheki.flashcards.dao.*;

public class Delete extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5381960810576430338L;
	private static final String DEFAULT_PATH = "http://localhost:8080/WebFlashCards";

	public void service(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String referer = request.getParameter("referer");
		String type = request.getParameter("type");
		String id = request.getParameter("id");

		try {
			CardDAO cardDao = new CardDAO();
			CategoryDAO catDao = new CategoryDAO();
			UserDAO userDao = new UserDAO();

			if (type.equals("user")) {
				User user = userDao.getUserById(Integer.parseInt(id));
				user.setName(request.getParameter("name"));
				userDao.deleteUser(user);
				referer = DEFAULT_PATH + "/index.jsp";
			}
			else if (type.equals("cat")) {
				Category cat = catDao.getCategoryById(Integer.parseInt(id));
				cat.setName(request.getParameter("name"));
				catDao.deleteCategory(cat);
				referer = DEFAULT_PATH + "/index.jsp";
			}
			else if (type.equals("card")) {
				Card card = cardDao.getCardById(Integer.parseInt(id));
				card.setFront(request.getParameter("front"));
				card.setBack(request.getParameter("back"));
				cardDao.deleteCard(card);
			}

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		response.setCharacterEncoding("UTF-8");
		response.sendRedirect(referer);
	}

}